package org.intelligentsia.keystone.updater;

import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * 
 * @author <a href="mailto:jguibert@intelligents-ia.com" >Jerome Guibert</a>
 */
public class UpdateInformation extends Link {

	private static final long	serialVersionUID	= -6430115176146602066L;
	private final List<Link>	plugins				= new ArrayList<Link>();

	public UpdateInformation() {
		super();
	}

	public UpdateInformation(final JSONObject json) throws JSONException {
		super(json);
		final JSONArray oplugins = json.optJSONArray("plugins");
		if (oplugins != null) {
			for (int i = 0; i < oplugins.length(); i++) {
				plugins.add(new Link(oplugins.optJSONObject(i)));
			}
		}
	}

	public List<Link> getPlugins() {
		return plugins;
	}

	public UpdateInformation addPlugin(final String name, final int version, final String url) {
		plugins.add(new Link(name, version, url));
		return this;
	}

	public UpdateInformation addPlugin(final String name, final int version, final String url, final String checksum) {
		plugins.add(new Link(name, version, url, checksum));
		return this;
	}

	public JSONObject toJSONObject() {
		return new JSONObject(this);
	}

	@Override
	public String toString() {
		return "UpdateInformation{" + super.toString() + ", plugins=" + plugins + '}';
	}

	@Override
	public boolean equals(final Object obj) {
		if (!super.equals(obj)) {
			return false;
		}
		final UpdateInformation other = (UpdateInformation) obj;
		if ((plugins != other.plugins) && ((plugins == null) || !plugins.equals(other.plugins))) {
			return false;
		}
		return true;
	}

	@Override
	public int hashCode() {
		int hash = super.hashCode();
		hash = 31 * hash + (plugins != null ? plugins.hashCode() : 0);
		return hash;
	}

	public static UpdateInformation read(final Reader reader) throws IOException, JSONException {
		final char cbuf[] = new char[1024];
		int c = 0;
		final StringBuilder buffer = new StringBuilder("");
		while (c != -1) {
			c = reader.read(cbuf, 0, 1024);
			if (c > 0) {
				buffer.append(cbuf, 0, c);
			}
		}
		return new UpdateInformation(new JSONObject(buffer.toString()));
	}

	public static void write(final Writer writer, final UpdateInformation updateInformation) throws IOException {
		writer.append(updateInformation.toJSONObject().toString());
	}
}
